//
//  BQNavigatorRunner.m
//  BQNavigator
//
//  Created by Zhiqiang Bao on 15-4-3.
//  Copyright (c) 2015年 Zhiqiang Bao. All rights reserved.
//

#import "BQNavigatorRunner.h"
#import "UIViewController+BQTop.h"
#import <objc/runtime.h>

@implementation BQNavigatorRunnerOption

+ (instancetype)optionWithCarrier:(UIViewController *)carrier param:(NSDictionary *)param animated:(BOOL)animated
{
    BQNavigatorRunnerOption *option = [[self alloc] init];
    
    option.carrier = carrier;
    option.param = param;
    option.animated = animated;
    
    return option;
}

@end

@implementation BQNavigatorRunner

- (id)runOrder:(BQNavigatorOrder *)order withOption:(BQNavigatorRunnerOption *)option
{
    id result = [super runOrder:order withOption:option];
    
    UIViewController *carrier = option.carrier;
    
    if (carrier == nil) {
        carrier = [UIViewController topNavigationController];
    }
    
    if (carrier == nil) {
        carrier = [UIViewController topViewController];
    }
    
    BQNavigatorOrderType type = order.type;
    UIViewController<BQNavigatable> *object = order.lastObject;
    
    if (type == BQNavigatorOrderTypeMultiton || object == nil) {
        
        Class cls = objc_getClass(order.className.UTF8String);
        
        if ([cls isSubclassOfClass:[UIViewController class]] &&
            class_respondsToSelector(cls, @selector(initWithEvent:))) {
            object = [[cls alloc] initWithEvent:order.event];
        }
        
        order.lastObject = object;
    }
    
    [self openViewController:object withCarrier:carrier animated:option.animated];
    
    return result;
}

- (void)openViewController:(UIViewController *)object withCarrier:(UIViewController *)carrier animated:(BOOL)animated
{
    if (object == nil || carrier == nil) return;
    
    if ([object isKindOfClass:[UINavigationController class]]) {
        [carrier presentViewController:object animated:animated completion:nil];
    } else if ([object isKindOfClass:[UIViewController class]]) {
        
        // If this object has been open then ignore it, or open it
        if (!object.navigationController && !object.presentingViewController) {
            if ([carrier isKindOfClass:[UINavigationController class]]) {
                [(UINavigationController *)carrier pushViewController:object animated:animated];
            } else if ([carrier isKindOfClass:[UIViewController class]]) {
                [carrier presentViewController:object animated:animated completion:nil];
            }
        }
    }
}

@end
